//
//  Login_Vc.swift
//  LocaLink
//
//  Created by eme on 2016/12/12.
//  Copyright © 2016年 Icy. All rights reserved.
//

/*
 owner:cy
 update:2016年12月23日21:21:29
 info: 首页
 */
import RxSwift
import UtilCore

class Home_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var buttons_Cv: UICollectionView!
    
    @IBOutlet weak var saoyisao_Btn: UIButton!
    
    @IBOutlet weak var efob_Btn: UIButton!
    
    @IBOutlet weak var ekey_Btn: UIButton!
    @IBOutlet weak var slide_Content_V: UIView!
    @IBOutlet weak var button_Content_V: UIView!
    //    @IBOutlet weak var slide_Sv: SlidBar!
    
    
    @IBOutlet weak var development_Btn: UIButton!
    /*----------------------------   自定义属性区域    ----------------------------*/
    
    
    
    
    var buttons:[(title:String,image:String,url:String,btnType:String)] =
        [
            ("NOTICE","noticeimg","http://101.200.203.219:920/notice.html","notice"),
            ("DELIVERY","deliveryimg","http://101.200.203.219:920/mydelivery.html","delivery"),
            ("REPORT","reportimg","http://101.200.203.219:920/Report.html","report"),
            ("KEY TRANSFER","transferimg","http://101.200.203.219:920/keytransfer.html","transfer"),
            ("KEY HOLDING","holdingimg","http://101.200.203.219:920/keyholding.html","holding"),
            ("SERVICE","serviceimg","http://101.200.203.219:920/service.html","service")
            
    ]
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.buttons_Cv.reloadData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        
        //        if let mapVc = self.storyboard?.instantiateViewControllerWithIdentifier("Development_Map_Vc") as? Development_Map_Vc {
        //            mapVc.isModal = true
        //            let naVc = UINavigationController(rootViewController: mapVc)
        //            self.presentViewController(naVc, animated: true, completion: nil)
        //        }
        //        self.content_V.changeBorderColor(UIColor.basic(), cornerRadius: self.content_V.frame.size.height/2 - 12, borderWidth: 2)
        self.development_Btn.changeBorderColor(UIColor.clear, cornerRadius: self.development_Btn.frame.size.height/2, borderWidth: 1)
        self.development_Btn.changeEdgeLeftImage(5)
        //        self.slide_Sv.delegate = self
        
        self.slide_Content_V.changeBorderColor(UIColor.clear, cornerRadius: 6, borderWidth: 1)
        self.button_Content_V.changeBorderColor(UIColor.clear, cornerRadius: 6, borderWidth: 1)
        
        //        self.slide_Sv.unlockSubject.subscribeNext{[unowned self] _ in
        //            self.openDoor()
        //        }.addDisposableTo(disposeBag)
    }
    func openDoor()  {
        let loginUser = LoginedUserPro.sharedInstance
        
        MDManager.shared().openDoor(withUserId: "\(loginUser.model!.user.phone)", useKeyId: pId, keyName: lockId, community: community, success:{ keyInfo in
            self.view.toast("success")
        }, failure: { error in
            self.showErrorPage()
        })
    }
    
    func showErrorPage()  {
        let errorPageVc = self.storyboard?.instantiateViewController(withIdentifier: "ErrorPage_Vc") as! ErrorPage_Vc
        errorPageVc.didTryAgain_Block = {[unowned self] _ in
            self.openDoor()
        }
        self.present(errorPageVc, animated: false, completion: nil)
    }
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        self.saoyisao_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.InnerStyle()
            })
            .disposed(by: disposeBag)
        self.development_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                if let mapNav = self.storyboard?.instantiateViewController(withIdentifier: "Development_Map_Nav") {
                    self.present(mapNav, animated: true, completion: nil)
                }
            })
            .disposed(by: disposeBag)
        self.efob_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                MDManager.shared().openDoor(withUserId: phone, useKeyId:lockId , keyName: pId, community: community, success:{ keyInfo in
                    self.view.toast("success")
                }, failure: { error in
                    //              self.showErrorPage()
                    //                        self.showErrorPage()
                })
            })
            .disposed(by: disposeBag)
        
        self.ekey_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                MDManager.shared().openDoor(withUserId: "18610201538", useKeyId:"BLZXA151001999" , keyName: "00000002&#20991230&#MD_BLZX_C5F4&#BEF4D7A8DFC179B52083E4B65ACD0C6BF1FF69CA6CA4F15CB00937F778FEE19F&#15A337D233E1DD9B4A15CA34E7F69470&#881B9902C5F4&#BLZXA151001999", community: "10002000515", success:{ keyInfo in
                    self.view.toast("success")
                }, failure: { error in
                    //
                    //                    self.showAlert("\(error.rawValue)", title: "错误码"){ _ in
                    //
                    //                    }
                    //                        self.showErrorPage()
                })
            })
            .disposed(by: disposeBag)
        
        
        
        
        //        self.slide_Sv.didUpdateBlock = { isOpen in
        //            if isOpen {
        //                if let loginUser = self.loginedUser.model {
        //                    MDManager.sharedManager().openDoorWithUserId("\(loginUser.user.phone)", useKeyId: pId, keyName: lockId, community: departId, success:{ keyInfo in
        //                        self.view.makeEmeToast("success")
        //                        }, failure: { error in
        //                            print( error)
        //                    })
        //                }
        //            }else{
        //                if let loginUser = self.loginedUser.model {
        //                    MDManager.sharedManager().openDoorWithUserId("\(loginUser.user.phone)", useKeyId: pId, keyName: lockId, community: departId, success:{ keyInfo in
        //                        self.view.makeEmeToast("success")
        //                        }, failure: { error in
        //                            print( error)
        //                    })
        //                }
        //
        //            }
        //        }
    }
    /// -无边框，内嵌4个角
    func InnerStyle() {
        
        //        //设置扫码区域参数
        //        var style = LBXScanViewStyle()
        //        style.centerUpOffset = 44;
        //        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner;
        //        style.photoframeLineW = 2;
        //        style.photoframeAngleW = 18;
        //        style.photoframeAngleH = 18;
        //        style.isNeedShowRetangle = false;
        //
        //        style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid;
        //
        //        style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0)
        //
        //
        //        style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_full_net")
        //
        //
        //        let vc = LBXScanViewController();
        //        vc.hidesBottomBarWhenPushed = true
        //        vc.title = "SCAN"
        //        vc.qRScanView?.labelReadying?.text = ""
        //        vc.scanStyle = style
        //        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    /**
     自定义leftBarButtonItem
     */
    override func customLeftBarButtonItem()  {
        
    }
    
    
    
}
//extension Home_Vc:SnappingSliderDelegate{
//
//    func snappingSliderDidIncrementValue(slider:SnappingSlider){
//        if let loginUser = self.loginedUser.model {
//            MDManager.sharedManager().openDoorWithUserId("\(loginUser.user.phone)", useKeyId: pId, keyName: lockId, community: departId, success:{ keyInfo in
//                self.view.makeEmeToast("success")
//                }, failure: { error in
//                    print( error)
//            })
//        }
//    }
//    func snappingSliderDidDecrementValue(slider:SnappingSlider){
//        if let loginUser = self.loginedUser.model {
//            MDManager.sharedManager().openDoorWithUserId("\(loginUser.user.phone)", useKeyId: pId, keyName: lockId, community: departId, success:{ keyInfo in
//                self.view.makeEmeToast("success")
//                }, failure: { error in
//                    print( error)
//            })
//        }
//    }
//
//}
// MARK: - UICollectionViewDataSource


// MARK: - UICollectionViewDataSource
extension Home_Vc:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return buttons.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonsCCell", for: indexPath) as!ButtonsCCell
        cell.item = buttons[indexPath.row]
        return cell
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 1
    }
}
extension Home_Vc:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        //        if let webVc = self.storyboard?.instantiateViewControllerWithIdentifier("Web_Vc") as? Web_Vc {
        //            webVc.webUrl = self.buttons[indexPath.row].url
        //            webVc.ishideNavBar = false
        //            webVc.rightBtnType = self.buttons[indexPath.row].btnType
        //            self.navigationController?.pushViewController(webVc, animated: true)
        //        }
        
        _ = self.buttons[indexPath.row].url.openURL()
    }
}

extension Home_Vc:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        
        return CGSize(width: self.buttons_Cv.frame.size.width/3, height: self.buttons_Cv.frame.size.height/2)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        return CGSize.zero
    }
}
